package xupt.com.bolg.zhifubao;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;

@Controller
public class PayController {
    private final static String APP_ID = "2016101700704194";
    private  final static String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCefJbInUq0sAybFfRH1wjnzX9ZEMdfZXY/XPpbIfnw4Q6Ux+sN1SGQwSWAJ7CwuI8vDRx17NRMBK3DMhI+PV2on4hMId8sAtBHIQmK1A2Ot6nHW3ipf0B4gJz357CVsF5JwT4+qq1fFyYdqrd0+caklmBOCud+/dzoSycvI9TkY8q5eUjx1wFS9Kd1vaCUm2dsewv/E+NHA9/NRoYBwDksfBs9fVzaSCdNJo9JXtA7rtU4WtRCII8y8eApxIvXwN7PrXjJrvcOukZZcTFeNIGMwwYqOlsoMbZ8VpjeQi6JRlE2xT4Dncsqb2kLOnkJ65FhT9IT8k+pEIW7YMeySyvFAgMBAAECggEARvMpoXfhCNDDY+5JJJwcjYFOoHXFe2x1qloabg/gz7hBCdQR42hllWMSQbQDAqos13h8JEK4q6twirDwv9JDCokYwFRtj0tXKHCez/qscxa/t9K4StD/8LJLEyQyxmBlZYlQL0fDQ42eb6uMY56qEeaMCIQTLKPDcG6shQr6dJ+PKGxNCYsEOY7/4/ycT9+VErBF2oje7cXmbodzj2nggDusR2i7Nfm95joIUJG3is/D5AAQlk6U5v2IbwONu0rPRi6catRE3VqFoj0XXr3xvz/svBWEgAuB1VZQLeN54L6r7t1+sq/HSCBgOuNkSeF2PbigdQEyI6tWKKIw+44tpQKBgQDaDHypvN67mesVo8FUelcI6Wc/hBTz2wc7klr19Pt4joM5oHBtzLBbQEEFSJD0Y8/1eTSwiEYXln2zpqZfP3TSToalrBArjxJsv3fZQU5pu1zC/gk2nKUNroaI4Reao/JxASK6alsxcTqoPSqhImLX2LYfh74xKc6DwcpX058nAwKBgQC6EjeRZUqpT8dWpvSOGUX1LKN+5ybiuqz73b/WhxJA+m1PojmGXbYyt0XmVQF6dglhAnMnulB6ndHmgsBilNq9/eKKrkabqxRcjGY+MMyTPV0wG22LflALNmV3V3zlniO2oJ2SCbYcLjgcAKFFbPWO1DesMttKmO7fL7EkAMdjlwKBgQCgxO4xtHlBNzZ26RuFrwJ3Jqii0z8joY3OpZV9ndjARcuJdLsQqggp79FBFQUTvHg7lNd9haywfZxHFou61K3M1ms+wgPWKhI6rl2uiRFIsgWuG+ItKwgjc1fsmpJtyY3bNiwl6H8+kC7gluDUl+brIPT/gHWCCEIlMYCAix7ggwKBgCysqQjQsA9cpzin1zmy2bgW4p5ac1ymg1fpkuC4B2rwdYRUJ8maAF/G3xKBQFydsHzJMMrOEfqOn9HffL9ui+Jn7ZdsZmmDttzNnNK7trJ3XkNponCGgENg6RWxPLyIrnxvrcVdbYrwkeovQIlBsud7Dm7auwn7FAckFTzWrwi7AoGAdSUe71QJYSQhug5UhYjubi0hV/mbcCL6ISCy1/dwagkuYZgcCNnpnUfHVrvrvBzkL/SCS1G9tZnIgMGefD31A0v+RNKitNzrAev0FsmEkyKoaPd1nfIUIWhI+J5IhNG9c40bShuhyPtSXAiNZGTZ32VT520nTb0lbowHM39JuUY=";

    private final static String CHARSET = "UTF-8";
    private final static String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAm52/jGtSIkE1zKjWxAEf3zbl7F0gV1LurDzrzSmENd8Dbr7cuAtmgLqF+wArY+Uk6aSbcI0mPpatqlmDm7tpWkPNUdjumyMUQn3OMo61tfO+1gWZy+l+8ShS6uJq78ntoBM6JLsBf8cPwjbbku9AyOBX04IRiwNUcOT5riWN7aZaRKy2Abg3ZGr67lTqSt2ITmWkT8NJe3WFnYxSCDh+b4HMlHblUUSTR1Rq6wOqIx9jHNT2ItsH8YAQaeoDz6IlZWO0APtE16YN2xVL/5suyC0V0Re2iwrYeBFt0wVXxFrEuy0oPZ2dGeYpf0i9O37Xm1hjjTMdRN8TyS5fOxw8pQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final static String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final static String FORMAT = "JSON";
    //签名方式
    private static String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private static String NOTIFY_URL = "http://127.0.0.1:8080/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private static String RETURN_URL = "http://127.0.0.1:8080/returnUrl";


    @RequestMapping("/alipay")
    public void alipay(HttpServletResponse httpResponse, HttpServletRequest request3) throws IOException {
        Random r=new Random();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = UUID.randomUUID().toString();

        int money=100;
        //付款金额，必填
        String total_amount =Integer.toString(money);

        //订单名称，必填
        String subject ="充值爱豆";
        //商品描述，可空
        String body = "爱豆可以为你认为写的好的博主打赏，回报他们的辛苦付出";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
//    /**
//     *
//     * @Title: AlipayController.java
//     * @Package com.sihai.controller
//     * @Description: 支付宝异步 通知页面
//     * Copyright: Copyright (c) 2017
//     * Company:FURUIBOKE.SCIENCE.AND.TECHNOLOGY
//     *
//     * @author sihai
//     * @date 2018年11月23日 下午8:51:13
//     * @version V1.0
//     */
//		@RequestMapping(value = "/alipayNotifyNotice")
//		@ResponseBody
//		public String alipayNotifyNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {
//
//			System.out.println("支付成功11111111111");
//
//			//获取支付宝POST过来反馈信息
//			Map<String,String> params = new HashMap<String,String>();
//			Map<String,String[]> requestParams = request.getParameterMap();
//			for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
//				String name = (String) iter.next();
//				String[] values = (String[]) requestParams.get(name);
//				String valueStr = "";
//				for (int i = 0; i < values.length; i++) {
//					valueStr = (i == values.length - 1) ? valueStr + values[i]
//							: valueStr + values[i] + ",";
//				}
//				//乱码解决，这段代码在出现乱码时使用
////				valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//				params.put(name, valueStr);
//			}
//
//			boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); //调用SDK验证签名
//
//			//——请在这里编写您的程序（以下代码仅作参考）——
//
////			 实际验证过程建议商户务必添加以下校验：
////			1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
////			2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
////			3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
////			4、验证app_id是否为该商户本身。
//
//			if(signVerified) {//验证成功
//				//商户订单号
//				String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
//
//				//支付宝交易号
//				String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
//
//				//交易状态
//				String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
//
//				//付款金额
//				String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
//
//				if(trade_status.equals("TRADE_FINISHED")){
//					//判断该笔订单是否在商户网站中已经做过处理
//					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
//					//如果有做过处理，不执行商户的业务程序
//
//					//注意： 尚自习的订单没有退款功能, 这个条件判断是进不来的, 所以此处不必写代码
//					//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
//				}else if (trade_status.equals("TRADE_SUCCESS")){
//					//判断该笔订单是否在商户网站中已经做过处理
//					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
//					//如果有做过处理，不执行商户的业务程序
//
//					//注意：
//					//付款完成后，支付宝系统发送该交易状态通知
//
//					// 修改叮当状态，改为 支付成功，已付款; 同时新增支付流水
//
//				}
//				System.out.println("111支付成功");
//
//			}else {//验证失败
//
//			}
//
//			return "success";
//		}

}

